package xml;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


import dbConn.DBConn;



/**
 * De XML-Parser
 * @author faceoff
 *
 */
public class LeesXML {
	public Hashtable<Integer,Container> aanvoer = new Hashtable<Integer,Container>();
	private DBConn db1;
	
	/**
	 * Constructor
	 * Opent connectie met de Database
	 * @param db
	 */
	public LeesXML(DBConn db) {
		this.db1 = db;
	}
	

	/**
	 * Open de XML en start het Parsen
	 * @param XMLFile String containing the location of the XML File 
	 */
	public void OpenXML(String XMLFile) 
	throws IOException, ParserConfigurationException, SAXException {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource(new FileReader(XMLFile));
			Document document = db.parse(is);
			insert(document);
	}
	
	/**
	 * Plaats de gevonden containers in de NodeList
	 * @param document
	 */
	public void insert(Document document) {
	    NodeList containers = document.getElementsByTagName("record");
	    for (int i = 0; i < containers.getLength() ; i++) {		//Stop de loop ;)
	    		aanvoer.put(aanvoer.size(), new Container(db1,(Element)containers.item(i)));
	    }
	    
	}
	
	/**
	 * Leeg de Stack naar de DB 
	 */
	public void naarDB() {
		for (int i = 0; i < aanvoer.size(); i++) {
			aanvoer.get(i).toDatabase();
		}
	}
}